﻿using BW.Mes.WinForms.Production.ProductionCommon;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using static BW.Mes.WinForms.Production.ProductionCommon.MainForm;

namespace BW.Mes.WinForms.Production.ProductionState
{
    public partial class ProduceFalseForm : DevExpress.XtraEditors.XtraForm
    {
        // 存储所有数据，用于分页
        private List<ProductionState> _allData;

        public ProduceFalseForm()
        {
            InitializeComponent();

            // 初始化分页控件事件
            InitPagination();
        }

        /// <summary>
        /// 初始化分页控件
        /// </summary>
        private void InitPagination()
        {
            // 设置默认每页显示条数
            int pageSize = 3; // 根据图片显示，设置默认为3条
            this.userControl1.PageSize = pageSize;

            // 订阅分页事件
            this.userControl1.ClickPageButtonEvent += UserControl1_ClickPageButtonEvent;
            this.userControl1.ChangedPageSizeEvent += UserControl1_ChangedPageSizeEvent;
            this.userControl1.JumpPageEvent += UserControl1_JumpPageEvent;
        }

        /// <summary>
        /// 分页按钮点击事件处理
        /// </summary>
        private void UserControl1_ClickPageButtonEvent(int currentPage)
        {
            // 应用分页
            ApplyPagination();
        }

        /// <summary>
        /// 每页显示条数改变事件处理
        /// </summary>
        private void UserControl1_ChangedPageSizeEvent()
        {
            // 应用分页
            ApplyPagination();
        }

        /// <summary>
        /// 跳转页面事件处理
        /// </summary>
        private void UserControl1_JumpPageEvent(int jumpPage)
        {
            // 应用分页
            ApplyPagination();
        }

        /// <summary>
        /// 设置网格列绑定
        /// </summary>
        public void InitGridColumn()
        {
            //绑定数据列到实体类属性
            this.Type.FieldName = "ProductionType";
            this.Code.FieldName = "ProductionCode";
            this.Process.FieldName = "Process";
            this.date.FieldName = "ProductionDateTime";
            //日期
            this.date.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
            this.date.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
            this.Desc.FieldName = "ProductionDesc";
            this.createby.FieldName = "CreatedBy";
            this.createda.FieldName = "CreatedAt";
            //日期
            this.createda.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
            this.createda.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
        }

        /// <summary>
        /// 自动序列化
        /// </summary>
        private void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                // 计算实际序号（考虑分页）
                int rowIndex = e.RowHandle + (this.userControl1.CurrentPage - 1) * this.userControl1.PageSize + 1;
                e.Info.DisplayText = rowIndex.ToString();
            }
        }

        /// <summary>
        /// 加载页面
        /// </summary>
        private async void gridControl1_Load(object sender, EventArgs e)
        {
            InitGridColumn();
            await LoadData();
        }

        /// <summary>
        /// 显示
        /// </summary>
        public async Task LoadData()
        {
            string falseUrl = ProduceConst.PRODUCE_FALSE;

            var result = await ProduceHttpClientHelper.RequestUrl(ProduceRequestType.get, falseUrl);

            try
            {
                // 反序列化为列表类型
                var showFalse = JsonConvert.DeserializeObject<ProduceApiResult<List<ProductionState>>>(result);

                if (showFalse.Success == true && showFalse.Data != null)
                {
                    // 保存所有数据
                    _allData = showFalse.Data;

                    // 计算总页数
                    int totalPages = (_allData.Count + this.userControl1.PageSize - 1) / this.userControl1.PageSize;
                    if (totalPages < 1) totalPages = 1;

                    // 更新分页控件
                    this.userControl1.TotalRows = _allData.Count;
                    this.userControl1.TotalPages = totalPages;
                    this.userControl1.CurrentPage = 1;

                    // 更新页码显示
                    this.userControl1.PageInfo.Text = $"第{this.userControl1.CurrentPage}/{totalPages}页";

                    // 应用分页
                    ApplyPagination();

                    if (_allData.Count == 0)
                    {
                        XtraMessageBox.Show("未查询到符合条件的数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载数据出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 应用分页
        /// </summary>
        private void ApplyPagination()
        {
            if (_allData == null)
                return;

            // 计算当前页数据
            int startIndex = (this.userControl1.CurrentPage - 1) * this.userControl1.PageSize;
            var pageData = _allData.Skip(startIndex).Take(this.userControl1.PageSize).ToList();

            // 更新数据源
            this.gridControl1.DataSource = pageData;
            this.gridControl1.RefreshDataSource();
        }

        /// <summary>
        /// 解锁按钮点击事件
        /// </summary>
        private async void UnLock_Click(object sender, EventArgs e)
        {
            // 创建ID列表，存储选中的记录ID
            List<long> selectedIds = new List<long>();

            // 遍历gridView1中的所有行
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                // 获取当前行的Ids值
                bool isSelected = Convert.ToBoolean(gridView1.GetRowCellValue(i, "Ids"));

                // 如果该行被选中
                if (isSelected)
                {
                    // 获取该行的Id值并添加到列表中
                    long id = Convert.ToInt64(gridView1.GetRowCellValue(i, "Id"));
                    selectedIds.Add(id);
                }
            }
            // 检查是否有选中的记录
            if (selectedIds.Count == 0)
            {
                XtraMessageBox.Show("请至少选择一条记录进行解锁", "提示");
                return;
            }

            // 确认是否要解锁所选记录
            DialogResult result = XtraMessageBox.Show($"确定要解锁选中的{selectedIds.Count}条记录吗？", "确认解锁", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                bool allSuccess = true;
                StringBuilder errorMessages = new StringBuilder();
                int successCount = 0;

                // 逐个处理每个选中的ID
                foreach (long id in selectedIds)
                {
                    // 构建解锁API URL
                    string UnlockUrl = $"{ProduceConst.Update_FALSE}/{id}";

                    //发送PUT请求
                    var responseJson = await ProduceHttpClientHelper.RequestUrl(ProduceRequestType.put, UnlockUrl);
                    // 反序列化响应
                    var lockResponse = JsonConvert.DeserializeObject<ProduceApiResult<bool>>(responseJson);

                    if (lockResponse != null && lockResponse.Success)
                    {
                        successCount++;
                    }
                    else
                    {
                        allSuccess = false;
                        string errorMsg = lockResponse?.Message ?? "未知错误";
                        errorMessages.AppendLine($"ID {id} 解锁失败: {errorMsg}");
                    }
                }

                if (allSuccess)
                {
                    XtraMessageBox.Show("解锁成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else if (successCount > 0)
                {
                    XtraMessageBox.Show($"成功解锁 {successCount} 条记录，{selectedIds.Count - successCount} 条记录失败:\n{errorMessages}",
                        "部分成功", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    XtraMessageBox.Show($"所有记录解锁失败:\n{errorMessages}",
                        "失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                // 刷新数据
                await LoadData();
            }
        }

        /// <summary>
        /// 实体类
        /// </summary>
        public class ProductionState
        {
            public bool Ids { get; set; }

            public string ProductionType { get; set; }
            public string ProductionCode { get; set; }
            public string Process { get; set; }
            public DateTime ProductionDateTime { get; set; }
            public bool ProduceState { get; set; }
            public string ProductionDesc { get; set; }
            public long Id { get; set; }
            public bool IsDeleted { get; set; }
            public DateTime CreatedAt { get; set; }
            public string CreatedBy { get; set; }

            public string option { get; set; }
        }
    }
}